<template>
  <el-card class="editor-main" v-loading="is_loading">
    <div class="header-form" v-if="!preview_data">
      <el-button type="primary" @click="submit">提交问卷</el-button>
    </div>

    <h1 style="text-align:center">{{form.title}}</h1>
    <div>{{form.description}}</div>

    <div class="countdown-container" v-if="form.has_due">
      <vue-countdown-timer
        @end_callback="handle_due"
        :interval="1000"
        :start-time="0"
        :end-time="Math.ceil(Date.parse(form.due) / 1000)"
        :start-label="'距离开始'"
        :end-label="'距离结束'"
        :end-text="'已结束'"
        :day-txt="'天'"
        :hour-txt="'小时'"
        :minutes-txt="'分钟'"
        :seconds-txt="'秒'">
      </vue-countdown-timer>
    </div>

    <div class="qlist">

      <Question
        v-for="(question, index) in form.questions"
        :key="index"
        v-show="!form.questions[index].hide"
        :no="index"
        class="qbox"
        v-model="form.questions[index]"
        @answerChange="changeAnswer"
        :ref="'q-'+question.uuid">
      </Question>

      <el-card class="box-card qbox new-q-card" v-if="!preview_data">
        <el-button type="primary" @click="submit">提交问卷</el-button>
      </el-card>

    </div>
  </el-card>
</template>

<script>
import Vue from 'vue'
import VueCountdownTimer from 'vuejs-countdown-timer';
Vue.use(VueCountdownTimer);

import cookie from 'cookie'

import Question from '@/components/question/Question.vue'
import Questionnaire from '@/api/Questionnaire.js'

import InterlockHandler from '@/components/question/InterlockHandler.js'

export default {
  props: {
    preview_data: {
      default: null
    }
  },
  name : "fill",
  components: {
    Question
  },
  data () {
    const form = this.preview_data || {
      title: '问卷',
      description: '给我好好填',
      questions: [
      ],
    }
    return {
      is_loading: false,
      form: form,
      answers : [null, null, null, null],
      uid: cookie.parse(document.cookie).uid || ""
    }
  },
  mounted() {
    if (!this.preview_data) {
      this.update()
    } else {
      this.changeAnswer(0, null)
    }
  },
  methods: {
    update() {
      this.is_loading = true
      Questionnaire.get(this.$route.params.id)
        .then((response) => {
          if (response.data.has_due && Date.now() > Date.parse(response.data.due)) {
            this.$alert('问卷已截止', '截止', {
              confirmButtonText: 'OK',
              callback: () => this.$router.go(-1)
            });
          }
          Object.assign(this.form, response.data)
          this.answers = new Array(this.form.questions.length)
          this.answers.fill(null)
        })
        .catch((error) => {
          console.log(error)
          this.$notify({
            title: 'Could not reach the API.',
            message: error
          })
        })
        .finally(() => {
          this.changeAnswer(0, null)
          this.is_loading = false
        })
    },
    handle_due() {
      this.$message("问卷截止")
      if (this.form.type === "exam") {
        this.upload()
      } else {
        this.$router.go()
      }
    },
    submit() {
      let i
      for (i=0;i<this.form.questions.length;i++){
        if(this.form.questions[i].nullable)
          continue;
        if(this.answers[i] === null){
          i++;
          var msg = "第"+i+"题未填写"
          this.$alert(msg, msg, {
            confirmButtonText: 'OK',
          });
          return;
        }
      }
      console.log(this.answers)
      this.upload()
    },
    upload() {
      this.is_loading = true;
      this.$http.post("/api/result/api/fill?qnid=" + this.$route.params.id + "&uid=" + this.uid, this.answers)
        .then(() => {
          this.$message("成功")
          if (this.form.type === "exam") {
            this.$router.push("/examResult?qnid=" + this.$route.params.id + "&uid=" + this.uid)
          }
          if (this.form.type === "vote") {
            this.$router.push("/voteResult?qnid=" + this.$route.params.id)
          }
          this.$router.push("/thanks")
        })
        .catch((error) => {
          console.log(error)
          this.$notify({
            title: 'Could not reach the API.',
            message: error.response.data.detail || error.toString()
          })
        })
        .finally(() => this.is_loading = false)
    },
    changeAnswer(no,answer){
      this.answers[no] = answer
      console.log(JSON.stringify(this.answers))
      const state = InterlockHandler(this.form.questions, i => this.$refs['q-' + i][0].answer)
      this.form.questions.forEach(q => q.hide = state[q.uuid])
    }
  },
}
</script>

<style scoped lang="sass">
.editor-main
  max-width: 20cm
  margin: auto

.editor-head
 border: 0

.new-q-card
  text-align: center

.qtitle
  max-width: 10cm

.title-sep
  margin: .1cm

.title-box
  text-align: center
  margin: .5cm

.header-form
  text-align: right

.countdown-container
  border-top: 1px solid #ccc
  text-align: center
</style>

<style scoped>
.qlist {
  padding: 20px;
  border-top: 1px solid #ccc;
  border-bottom: 1px solid #ccc;
}
.qbox {
  width: 100%;
  margin-top: 20px;
  border-radius: 0;
}
.qbox:first-child {
  margin-top: 0;
}
.qbox-new {
  padding: 20px;
  border: 1px solid #dcdfe6;
  text-align: center;
}
</style>

